require'zsvc.appbase'
require'zdc.logger'
require'zsvc.accept'
require'zsvc.apphandle'
require'zsvc.notifycon'
require'zsvc.notifymag'
require'zsvc.appcon'
require'zsvc.telnetd'
require'zdc.clicmd'

module(..., package.seeall)

function NewReact(reactmod, params)
	reactmod = REACTMOD or 'zsvc.react'
	local react=require(reactmod).new(params)
	return react
end

function RunReact(react)
	while(1) do
		react:Dispatch(1)
	end
end

function AddSchedule(REACT,timeoutcb,timer)
	return REACT:AddEvent(nil,REACT.EV_TIMEOUR,timeoutcb,timer)
end

function StartAppD(REACT,cfg)
	local APP=cfg.app or assert(zsvc.appbase.new(cfg.DALCFG.ZLoadConf(cfg.APPCONF,cfg.DALCFG)),"can't create APP")
	return zsvc.accept.server(zsvc.apphandle.new,{host = cfg.HOST or "*",port = cfg.PORT or 9999,react=REACT,app=APP,logger=cfg.logger or zdc.logger.defaultlog})
end

function StartCliTelnetD(REACT,cfg)
	local LOGGER=cfg.logger or zdc.logger.defaultlog
	local APP=cfg.app or assert(zsvc.appbase.new(cfg.DALCFG.ZLoadConf(cfg.APPCONF,cfg.DALCFG)),"can't create APP")
	
	local function cmdtelnetnew(params)
		local tl=zsvc.telnetd.new(params)
		
		local myio={put=function (s,...) tl:vty_write(table.concat({...})) end}
		local ENV=zdc.clicmd.new(APP.dal,cfg.ROOTID or '',myio,LOGGER)
		tl.vty_prompt=function()
			ENV:_put_prompt()
		end
		tl.vty_hello=function()
			tl:vty_write("Hello, this is zdc command line\n")
		end
		tl.vty_complete_command=function(self)
			local cmd=ENV:docmd(self.vty:getbuf(),1)
			return cmd
		end
		tl.OnCliCmd=function(self,fd,cmd)
			if cmd=='!exit' then return nil end
			cmd=ENV:docmd(cmd,cmd:sub(#cmd)=='\t' or cmd:sub(#cmd)=='?')
			if cmd then self:vty_write(cmd) end
			if ENV._curmode=="END" then
				return nil
			end
			if not tl.vty then
				ENV:_put_prompt()
			else
			end
			return true
		end
		tl.vty_break=function()
			ENV:_close()
		end
		
		tl:start_tty()
		return tl
	end
	
	return zsvc.accept.server(cmdtelnetnew,{host=cfg.HOST or "*",port=cfg.PORT or 3000,react=REACT,app=APP,logger=LOGGER})
end

